/**
 * Product Variations Handler
 * 产品变体处理脚本
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    const ProductVariations = {
        init: function() {
            this.bindEvents();
            this.initVariationForms();
        },

        // 绑定事件
        bindEvents: function() {
            // 变体选择变化
            $(document).on('change', '.variation-select select', this.onVariationChange.bind(this));
            
            // 重置变体选择
            $(document).on('click', '.reset-variations', this.resetVariations.bind(this));
            
            // 变体图片切换
            $(document).on('click', '.variation-image', this.selectVariationImage.bind(this));
            
            // 数量调整
            $(document).on('click', '.qty-btn', this.adjustQuantity.bind(this));
        },

        // 初始化变体表单
        initVariationForms: function() {
            $('.variations_form').each(function() {
                const $form = $(this);
                ProductVariations.setupVariationForm($form);
            });
        },

        // 设置变体表单
        setupVariationForm: function($form) {
            const productId = $form.data('product_id');
            const variationsData = $form.data('product_variations');
            
            if (!variationsData) return;
            
            // 存储变体数据
            $form.data('variations', variationsData);
            
            // 初始化选择器
            this.initializeSelectors($form);
            
            // 检查初始状态
            this.checkVariationAvailability($form);
        },

        // 初始化选择器
        initializeSelectors: function($form) {
            const $selects = $form.find('.variation-select select');
            
            $selects.each(function() {
                const $select = $(this);
                const attribute = $select.attr('name');
                
                // 添加默认选项
                if (!$select.find('option[value=""]').length) {
                    $select.prepend('<option value="">Choose an option</option>');
                }
                
                // 设置初始值
                $select.val('');
            });
        },

        // 变体选择变化处理
        onVariationChange: function(e) {
            const $select = $(e.target);
            const $form = $select.closest('.variations_form');
            
            // 更新依赖选择器
            this.updateDependentSelectors($form, $select);
            
            // 检查变体可用性
            this.checkVariationAvailability($form);
            
            // 查找匹配的变体
            const variation = this.findMatchingVariation($form);
            
            if (variation) {
                this.updateVariationDetails($form, variation);
            } else {
                this.clearVariationDetails($form);
            }
        },

        // 更新依赖选择器
        updateDependentSelectors: function($form, $changedSelect) {
            const variations = $form.data('variations');
            const currentSelections = this.getCurrentSelections($form);
            
            $form.find('.variation-select select').each(function() {
                const $select = $(this);
                if ($select.is($changedSelect)) return;
                
                const attribute = $select.attr('name');
                const availableOptions = new Set();
                
                // 查找可用选项
                variations.forEach(variation => {
                    let matches = true;
                    
                    // 检查当前选择是否与此变体匹配
                    for (const [attr, value] of Object.entries(currentSelections)) {
                        if (attr !== attribute && value !== '' && variation.attributes[attr] !== value) {
                            matches = false;
                            break;
                        }
                    }
                    
                    if (matches && variation.is_in_stock) {
                        const optionValue = variation.attributes[attribute];
                        if (optionValue) {
                            availableOptions.add(optionValue);
                        }
                    }
                });
                
                // 更新选项状态
                $select.find('option').each(function() {
                    const $option = $(this);
                    const value = $option.val();
                    
                    if (value === '') return; // 跳过默认选项
                    
                    if (availableOptions.has(value)) {
                        $option.prop('disabled', false).show();
                    } else {
                        $option.prop('disabled', true).hide();
                        if ($option.is(':selected')) {
                            $select.val('');
                        }
                    }
                });
            });
        },

        // 检查变体可用性
        checkVariationAvailability: function($form) {
            const selections = this.getCurrentSelections($form);
            const allSelected = Object.values(selections).every(value => value !== '');
            
            const $addToCartBtn = $form.find('.single_add_to_cart_button');
            const $variationId = $form.find('input[name="variation_id"]');
            
            if (allSelected) {
                const variation = this.findMatchingVariation($form);
                if (variation && variation.is_in_stock) {
                    $addToCartBtn.prop('disabled', false).removeClass('disabled');
                    $variationId.val(variation.variation_id);
                } else {
                    $addToCartBtn.prop('disabled', true).addClass('disabled');
                    $variationId.val('');
                }
            } else {
                $addToCartBtn.prop('disabled', true).addClass('disabled');
                $variationId.val('');
            }
        },

        // 查找匹配的变体
        findMatchingVariation: function($form) {
            const variations = $form.data('variations');
            const selections = this.getCurrentSelections($form);
            
            return variations.find(variation => {
                return Object.entries(selections).every(([attr, value]) => {
                    return value === '' || variation.attributes[attr] === value;
                });
            });
        },

        // 获取当前选择
        getCurrentSelections: function($form) {
            const selections = {};
            
            $form.find('.variation-select select').each(function() {
                const $select = $(this);
                const attribute = $select.attr('name');
                const value = $select.val();
                selections[attribute] = value;
            });
            
            return selections;
        },

        // 更新变体详情
        updateVariationDetails: function($form, variation) {
            // 更新价格
            if (variation.price_html) {
                $form.find('.price').html(variation.price_html);
            }
            
            // 更新库存信息
            const $stockInfo = $form.find('.stock-info');
            if (variation.is_in_stock) {
                $stockInfo.html(`<span class="in-stock">In stock (${variation.stock_quantity || 'Many'} available)</span>`);
            } else {
                $stockInfo.html('<span class="out-of-stock">Out of stock</span>');
            }
            
            // 更新SKU
            if (variation.sku) {
                $form.find('.sku').text(variation.sku);
            }
            
            // 更新产品图片
            if (variation.image && variation.image.src) {
                this.updateVariationImage($form, variation.image);
            }
            
            // 更新数量限制
            const $qtyInput = $form.find('input[name="quantity"]');
            if (variation.max_qty) {
                $qtyInput.attr('max', variation.max_qty);
            }
            if (variation.min_qty) {
                $qtyInput.attr('min', variation.min_qty);
            }
        },

        // 清除变体详情
        clearVariationDetails: function($form) {
            // 恢复默认价格
            const $price = $form.find('.price');
            const originalPrice = $price.data('original-price');
            if (originalPrice) {
                $price.html(originalPrice);
            }
            
            // 清除库存信息
            $form.find('.stock-info').empty();
            
            // 重置数量限制
            const $qtyInput = $form.find('input[name="quantity"]');
            $qtyInput.attr('max', '').attr('min', '1');
        },

        // 更新变体图片
        updateVariationImage: function($form, image) {
            const $mainImage = $('.product-image-main img');
            const $thumbnails = $('.product-thumbnails');
            
            if ($mainImage.length) {
                // 保存原始图片（如果还没保存）
                if (!$mainImage.data('original-src')) {
                    $mainImage.data('original-src', $mainImage.attr('src'));
                    $mainImage.data('original-srcset', $mainImage.attr('srcset'));
                }
                
                // 更新主图片
                $mainImage.attr('src', image.src);
                if (image.srcset) {
                    $mainImage.attr('srcset', image.srcset);
                }
                
                // 更新alt属性
                $mainImage.attr('alt', image.alt || '');
            }
        },

        // 重置变体选择
        resetVariations: function(e) {
            e.preventDefault();
            
            const $form = $(e.target).closest('.variations_form');
            
            // 重置所有选择器
            $form.find('.variation-select select').val('').trigger('change');
            
            // 重置价格显示
            this.clearVariationDetails($form);
            
            // 恢复原始图片
            const $mainImage = $('.product-image-main img');
            const originalSrc = $mainImage.data('original-src');
            const originalSrcset = $mainImage.data('original-srcset');
            
            if (originalSrc) {
                $mainImage.attr('src', originalSrc);
                if (originalSrcset) {
                    $mainImage.attr('srcset', originalSrcset);
                }
            }
            
            // 禁用添加到购物车按钮
            $form.find('.single_add_to_cart_button').prop('disabled', true).addClass('disabled');
            $form.find('input[name="variation_id"]').val('');
        },

        // 选择变体图片
        selectVariationImage: function(e) {
            e.preventDefault();
            
            const $thumb = $(e.currentTarget);
            const newSrc = $thumb.data('large-image');
            const $mainImage = $('.product-image-main img');
            
            if (newSrc && $mainImage.length) {
                $mainImage.attr('src', newSrc);
                
                // 更新活动缩略图
                $('.variation-image').removeClass('active');
                $thumb.addClass('active');
            }
        },

        // 调整数量
        adjustQuantity: function(e) {
            e.preventDefault();
            
            const $btn = $(e.currentTarget);
            const $input = $btn.siblings('input[type="number"]');
            const currentVal = parseInt($input.val()) || 1;
            const min = parseInt($input.attr('min')) || 1;
            const max = parseInt($input.attr('max')) || 999;
            
            let newVal;
            if ($btn.hasClass('qty-increase')) {
                newVal = Math.min(currentVal + 1, max);
            } else {
                newVal = Math.max(currentVal - 1, min);
            }
            
            $input.val(newVal).trigger('change');
        }
    };

    // 文档加载完成后初始化
    $(document).ready(function() {
        ProductVariations.init();
    });

    // 全局暴露
    window.ProductVariations = ProductVariations;

})(jQuery);